package com.example.interceptor;

import com.example.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 令牌校验拦截器
 */
@Slf4j
@Component
public class TokenInterceptor  implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(request.getRequestURI().contains("/login")){
            log.info("登录操作,放行");
            return true;
        }

        String token = request.getHeader("token");
        if(token == null||token.isEmpty()){
            log.info("令牌为空,未登录");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);// 401
            return false;
        }

        try {
            JwtUtils.parseToken(token);
        }catch (Exception e){
            log.info("令牌非法,响应401");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);// 401
            return false;
        }
        log.info("令牌校验通过,放行");
        return true;
    }
}
